/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ereconquista.web;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.imageio.ImageIO;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author Claudio
 */
@ManagedBean
@ViewScoped
public class FileUploader  implements Serializable{
   
        
    @ManagedProperty(value = "#{aplicationBean}")
    private AplicationBean aplicationBean;
    
    @ManagedProperty(value = "#{publicacionBean}")
    private PublicacionBean publicacionBean;



    public AplicationBean getAplicationBean() {
        return aplicationBean;
    }

    public void setAplicationBean(AplicationBean aplicationBean) {
        this.aplicationBean = aplicationBean;
    }

    public PublicacionBean getPublicacionBean() {
        return publicacionBean;
    }

    public void setPublicacionBean(PublicacionBean publicacionBean) {
        this.publicacionBean = publicacionBean;
    }
    
       public void upload(FileUploadEvent event) {  
        
        // Do what you want with the file        
        try {
            copyFile(event.getFile().getFileName(), event.getFile().getInputstream());            
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }  

    public void copyFile(String fileName, InputStream in) {
           try {
               
               String[] split = fileName.split("\\.");
               String extension = split[split.length - 1].toLowerCase();               
               String nombreImagen = fileName;
               
//               System.out.println("Nombre imagen:" + nombreImagen);
               
               File targetFolder = new File(aplicationBean.getP().getPathUpload()+fileName);
               
//               System.err.println("Nombre archivo: "+targetFolder.getName());
               
               targetFolder.renameTo(targetFolder);
               
                // write the inputStream to a FileOutputStream
                OutputStream out = new FileOutputStream(targetFolder);
             
                int read = 0;
                byte[] bytes = new byte[1024];
             
                while ((read = in.read(bytes)) != -1) {
                    out.write(bytes, 0, read);
                }
             
                in.close();
                out.flush();
                out.close();
                
                guardarImagen(aplicationBean.getP().getPathUpload()+nombreImagen, aplicationBean.getP().getPathUpload()+nombreImagen, extension);
              
                
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
    }
    
    private  void guardarImagen(String filePath,String outputFile, String formatoArchivo){
        try {

            BufferedImage sourceImage = ImageIO.read(new File(filePath));
            double width = sourceImage.getWidth();
            double height = sourceImage.getHeight();
            
            int widthFinal  = 800;
            int heightFinal = 1066;
            
            if(height<heightFinal && width<widthFinal){
                                
                heightFinal = (int) height;
                widthFinal = (int) width;
            }

            if(height>heightFinal){
                                
                //float extraSize=    width-widthFinal;
                double  percent = heightFinal/height;
                widthFinal = (int) (width*percent);
                
            }else{ 
                
                if(width>widthFinal){
                                        
                    double  percent = widthFinal/width;
                    heightFinal = (int) (heightFinal*percent);                    
                }
                
            }
            //Creamos un objeto imagen
            BufferedImage img = new BufferedImage(widthFinal, heightFinal, BufferedImage.TYPE_INT_RGB);                
            Image scaledImage = sourceImage.getScaledInstance(widthFinal, heightFinal, Image.SCALE_DEFAULT);                
            img.createGraphics().drawImage(scaledImage, 0, 0, null);                
            ImageIO.write(img, formatoArchivo, new File(outputFile));    

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
}
